#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : LineEdit.py
# Purpose  : 
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-07-03 17:53
# ==============================================================================
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit, QAction, QApplication, QStyle, QWidget
from conf.configuration import logger


class LineEdit(QLineEdit):
    def __init__(self, *args, **kwargs):
        super(LineEdit, self).__init__(*args, **kwargs)
        # self.setClearButtonEnabled(True)
        # action = QAction(QIcon(os.path.join(img_path, 'button-clear-search.png')), 'clear', self)
        self.textChanged.connect(self.text_changed)

    def text_changed(self):
        action = QAction(QApplication.style().standardIcon(QStyle.SP_DialogDiscardButton), 'clear', self)
        if not self.actions():
            self.addAction(action, QLineEdit.TrailingPosition)
            action.setVisible(False)
            action.triggered.connect(self.clear)
        logger.debug(f"text changed")
        logger.debug(f"{self.text()}")
        if self.text():
            action.setVisible(True)
        else:
            logger.debug(f"remove action")
            action.setVisible(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    win = QWidget()
    win.setFixedWidth(500)
    line = LineEdit(win)
    win.show()
    sys.exit(app.exec_())
